/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.DateUtil;
import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.BASE64Decoder;

/**
 *
 * @author 52461
 */
public class SK9000 {

    private String baseData;
    private String base2Data;
    private String device_code = "SK9000";
    private String code = "LA";
    private String sampletype = "全血";
    private String sampletypeId = null;

    public SK9000(String baseData) {
        this.baseData = baseData.replace("r", "#");

        parseComData();

    }

    public void parseComData() {
        try {
            String sampleNo = null;
            String testDate = DateUtil.getDate();
            String testTime = null;

            String cs[] = baseData.split("#######################")[0].split("#");
             String str = baseData.split("#######################")[0].replace("h", "1").replace("#", "1");
            List<String> list = new ArrayList<String>();
             sampleNo = str.substring(2, 11);
                System.out.println(sampleNo);

                list.add(str.substring(25, 28));
                list.add(str.substring(29, 32));
                list.add(str.substring(33, 36));//122

                list.add(str.substring(37, 40));//618
                list.add(str.substring(41, 44));//017
                list.add(str.substring(45, 48));//008
                list.add(str.substring(49, 52));//039
                list.add(str.substring(53, 56));//404
                list.add(str.substring(57, 60));//122
                list.add(str.substring(61, 64));//338
                list.add(str.substring(65, 69));//0839
                list.add(str.substring(70, 74));//0839
                list.add(str.substring(75, 79));//0839

                list.add(str.substring(80, 83));//0839
                list.add(str.substring(84, 87));//0839
                list.add(str.substring(88, 91));//0839
                list.add(str.substring(92, 95));//0839
                list.add(str.substring(96, 99));//0839
                list.add(str.substring(100, 103));//0839
                list.add(str.substring(104, 107));//0839
            
            System.out.println(list);
            System.out.println(list);
            Map<String, String> map = new HashMap<String, String>();
            if (list.size() > 18) {
                map.put("WBC", Integer.parseInt(list.get(0).substring(0, 2)) + "." + list.get(0).substring(2, 3));
                map.put("LYM%", Integer.parseInt(list.get(1).substring(0, 2)) + "." + list.get(1).substring(2, 3));
                map.put("MID%", Integer.parseInt(list.get(2).substring(0, 2)) + "." + list.get(2).substring(2, 3));
                map.put("GRA%", Integer.parseInt(list.get(3).substring(0, 2)) + "." + list.get(3).substring(2, 3));
                map.put("LYM#", Integer.parseInt(list.get(4).substring(0, 2)) + "." + list.get(4).substring(2, 3));
                map.put("MID#", Integer.parseInt(list.get(5).substring(0, 2)) + "." + list.get(5).substring(2, 3));
                map.put("GRA#", Integer.parseInt(list.get(6).substring(0, 2)) + "." + list.get(6).substring(2, 3));
                map.put("RBC", Integer.parseInt(list.get(7).substring(0, 2)) + "." + list.get(7).substring(2, 3));
                map.put("HGB", Integer.parseInt(list.get(8).substring(0, 2)) + "." + list.get(8).substring(2, 3));
                map.put("HCT", Integer.parseInt(list.get(9).substring(0, 2)) + "." + list.get(9).substring(2, 3));
                map.put("MCV", Integer.parseInt(list.get(10).substring(0, 3)) + "." + list.get(10).substring(3, 4));
                map.put("MCH", Integer.parseInt(list.get(11).substring(0, 3)) + "." + list.get(11).substring(3, 4));
                map.put("MCHC", Integer.parseInt(list.get(12)) + "");
                map.put("RDW-SD", Integer.parseInt(list.get(13).substring(0, 2)) + "." + list.get(13).substring(2, 3));
                map.put("RDW-CV", Integer.parseInt(list.get(14).substring(0, 2)) + "." + list.get(14).substring(2, 3));
                map.put("PLT", list.get(15));
                map.put("MPV", Integer.parseInt(list.get(16).substring(0, 2)) + "." + list.get(16).substring(2, 3));
                map.put("PDW", Integer.parseInt(list.get(17).substring(0, 2)) + "." + list.get(17).substring(2, 3));
                map.put("PCT", Integer.parseInt(list.get(18).substring(0, 1)) + "." + list.get(18).substring(1, 3));
                map.put("P-LCR", Integer.parseInt(list.get(19).substring(0, 2)) + "." + list.get(19).substring(2, 3));

                String images[] = baseData.split("#######################")[1].replaceAll("#+", "@").split("@");
                String imagep = images[images.length - 1].replace("&", "");

                map.put("image#WBC", getImagePoint(imagep.substring(0, 768)));
                map.put("image#RBC", getImagePoint(imagep.substring(768, 1536)));
                map.put("image#PLT", getImagePoint(imagep.substring(1536, 2304)));

                sendDb(Tool.getSampleNo(code, sampleNo), testDate, map);
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }
    }

    private String getImagePoint(String str) {
        char[] cs = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < cs.length; i += 3) {
            // System.out.println(str.substring(i, i + 3));
            sb.append(Integer.parseInt(str.substring(i, i + 3))).append(" ");
        }

        return sb.toString();
    }

    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
        // System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库" + key);
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();

            Record rs = Db.findFirst("select * from pp_device_test where TESTID='" + key.trim().replace("*", "") + "' AND DEVICEID='" + device_code + "'  limit 1");
            if (rs != null) {
                newMap.put("ITEMPK", rs.get("TESTPK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);

                if (rs.getStr("TESTID").equalsIgnoreCase("image#RBC") || rs.getStr("TESTID").equalsIgnoreCase("image#PLT")) {

                    newMap.put("RESULTFLAG", "1");//base64
                    // System.out.println("yyyyyyyyyy-----------------------");
                } else if (rs.getStr("TESTID").equalsIgnoreCase("image#WBC")) {
                    newMap.put("RESULTFLAG", "1");//散点图
                } else {
                    newMap.put("RESULTFLAG", "0");
                }
                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return true;

    }

    private void getChart(String baseData, Map<String, String> resultMap) {
        System.out.println(baseData.length() + "____________________________________");
        System.out.println("--------------------------------------" + baseData + "----------------------------------------------------" + baseData.length());
        String strs[] = baseData.split("87,72,105,115,116,111,68,97,116,97,22");
        String str[] = strs[1].split(",");
        String image_wbc = "";
        for (int i = 0; i < str.length; i++) {
            if (i < 250) {
                image_wbc += str[i] + " ";
            }
        }
        // System.out.println(data);
        resultMap.put("image#WBC", image_wbc);

        String strsr[] = baseData.split("82,72,105,115,116,111,68,97,116,97,22");
        String strr[] = strsr[1].split(",");
        String image_rbc = "";
        for (int i = 0; i < strr.length; i++) {
            if (i < 250) {
                image_rbc += strr[i] + " ";
            }
        }
        // System.out.println(data);
        resultMap.put("image#RBC", image_rbc);

        String strsp[] = baseData.split("80,72,105,115,116,111,68,97,116,97,22");
        String strp[] = strsp[1].split(",");
        String image_plt = "";
        for (int i = 0; i < strp.length; i++) {
            if (i < 129) {
                image_plt += strp[i] + " ";
            }
        }

        resultMap.put("image#PLT", image_plt);
    }

    private void getChart2(String baseData, Map<String, String> resultMap) {

        String WBC = baseData.split("WHistoData")[1].split("RBCHisto")[0];
        byte[] wbc = WBC.getBytes();
        String image_wbc = "";
        for (byte b : wbc) {
            image_wbc += b + " ";
        }
        resultMap.put("image#WBC", image_wbc);

        String RBC = baseData.split("RHistoData")[1].split("PLTHisto")[0];
        byte[] rbc = RBC.getBytes();
        String image_rbc = "";
        for (byte b : rbc) {
            image_rbc += b + " ";
        }
        resultMap.put("image#RBC", image_rbc);
        String PLT = baseData.split("PHistoData")[1];
        byte[] plt = PLT.getBytes();
        String image_plt = "";
        for (byte b : plt) {
            image_plt += b + " ";
        }
        resultMap.put("image#PLT", image_plt);
    }

    public static String encodeBase64(String data) {
        StringBuffer sb = new StringBuffer();

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    // b[i]+=256;
                    sb.append(b[i] + 256).append(" ");
                } else {
                    sb.append(b[i]).append(" ");
                }
                // System.out.println(b[i]);
            }
            //生成jpeg图片

            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

}
